package com.zyj.exam_app.login.controller;

import com.zyj.exam_app.context.UserContext;
import com.zyj.exam_app.login.bean.LoginInfo;
import com.zyj.exam_app.login.service.LoginService;
import com.zyj.exam_app.menu_manager.bean.MenuBean;
import com.zyj.exam_app.user_manager.bean.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    private  LoginService loginService;


    @RequestMapping("/login")
    public String loginPage(){
        return "login";
    }


    @RequestMapping("/index")
    public String indexPage(Model model){
        //验证是否登录
        LoginInfo loginInfo = UserContext.getCurreentUser();
        if(loginInfo == null){
            //没有登录，重定向到登录页面
            return "redirect:login";
        }
        //已经登录，获取菜单列表，转到主页面
        List<MenuBean> menus = loginInfo.getUserMenus();
        model.addAttribute("menus", menus);
        return "index";
    }

    @PostMapping( "/doLogin")
    @ResponseBody
    public Map<String, Object> doLogin(UserBean userInfo){
        //登录验证
        LoginInfo loginInfo = loginService.doLogin(userInfo);
        Map<String, Object> result = new HashMap<>();
        if(loginInfo != null){
            result.put("success", true);
        }else{
            result.put("success", false);
            result.put("info", "用户名与密码不匹配！");
        }
        return result;
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    public String logout(){
        UserContext.removeCurrentUser();
        return "redirect:login";
    }

}
